/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: CodeCheckInterceptor.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.network;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import io.bhex.baselib.network.Utils.CookieUtils;
import io.bhex.sdk.BhexSdk;
import io.bhex.sdk.account.EventLogin;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.enums.ERROR_CODE;
import io.bhex.baselib.network.response.BaseResponse;
import io.bhex.baselib.network.interceptor.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static okhttp3.internal.Util.UTF_8;

/**
 * 对于全局错误代码进行拦截处理
 */
public class CodeCheckInterceptor implements Interceptor {
    private CodeCheckListener mCodeCheckListener;

    public CodeCheckInterceptor(CodeCheckListener codeCheckListener) {
        mCodeCheckListener = codeCheckListener;
    }

    @Override
    public Request intercept(Request request, okhttp3.Interceptor.Chain chain) {
        return request;
    }

    @Override
    public Response intercept(Response response, okhttp3.Interceptor.Chain chain) throws IOException {
//        if (response == null || !response.isSuccessful()) {
        if (response == null || !isSuccess(response.code())) {
            return response;
        }

        ResponseBody body = response.body();
        if (body == null)
            return response;

        body.source().request(Long.MAX_VALUE);
        BaseResponse data=null;
        try {
            data= JSON.parseObject(body.source().buffer().clone().readString(body.contentType() != null ? body.contentType().charset(UTF_8) : UTF_8),
                   BaseResponse.class);
            //okHttp 4.0.1
//            data= JSON.parseObject(body.source().buffer().clone().readString(body.contentType() != null ? body.contentType().charset(Charset.forName("UTF-8")) : Charset.forName("UTF-8")),
//                   BaseResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        if (data == null || data.isSuccess())
        if (data == null)
            return response;

        String code = data.getCode();
        if (TextUtils.isEmpty(code)) {
            return response;
        }else{
            //TODO XXX  全局请求拦截 业务处理，例如token失效，重新登录等..

//        if (!code.equals(ERROR_CODE.ERROR_CODE_300021.getCode()) && !code.equals(ERROR_CODE.ERROR_CODE_300031.getCode())
//                && !code.equals(ERROR_CODE.ERROR_CODE_300032.getCode())&& !code.equals(ERROR_CODE.ERROR_CODE_300030.getCode())) {
//            MiscUtil.showDIYToast(BHexApplication.getInstance(), data.getMsg());
//        }
//
        if (code.equals(ERROR_CODE.NO_LOGIN.getCode())){
            UserInfo.clearUserInfo();
            CookieUtils.clearCookies(BhexSdk.getContext());
            EventBus.getDefault().post(new EventLogin());
            if (mCodeCheckListener != null) {
                String msg = data.getMsg();
                mCodeCheckListener.noLoginNotify(msg);
            }
        }
//        else if (code.equals(ERROR_CODE.NO_LOGIN_TRADE.getCode())) {
//            CommonFunc.jumpTradeLogin(BHexApplication.getInstance());
//        }
        }


        return response;
    }

    private boolean isSuccess(int code){
        return (code >= 200 && code < 300)|| code ==400 || code==500 ;
    }

    public interface CodeCheckListener{
        void noLoginNotify(String msg);
    }
}